package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
        @Autowired
        private CategoryMapper categoryMapper;
    @Override
    //查询所有分类
    public List<Category> findAll() {
        //调用mapper
        List<Category> list=categoryMapper.findAll();
        return list;
    }
    //修改数据
    @Override
    public void updateById(Category category) {
        //补全参数
        //修改时间
       /* category.setCreateTime(new Date());
        category.setUpdateTime(new Date());
        //修改人
        category.setUpdateUser(1l);
        category.setCreateUser(1l);*/
        //调用mapper
        categoryMapper.update(category);
    }
    //新增菜品分类
    @Override
    public void save(Category category) {
        //补全信息
        //雪花算法
        long id = IdUtil.getSnowflake(1, 1).nextId();
        category.setId(id);
        //创建人
       /* category.setCreateUser(1l);
        category.setUpdateUser(1l);
        //创建时间
        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());*/
        //调用mapper
        categoryMapper.save(category);
    }


    // 删除分类
    @Override
    public void deleteById(Long id) {
        // 1.根据分类id查询菜品数量
        Integer dishCount = categoryMapper.countDishByCategoryId(id);
        if (dishCount>0) {
            throw new CustomException("该分类下有菜品，不允许删除");
        }
        // 2.根据分类id查询套餐数量
        Integer setmealCount = categoryMapper.countSetmealByCategoryId(id);
        if (setmealCount>0) {
            throw new CustomException("该分类下有套餐，不允许删除");
        }
        // 3.根据id删除分类
        categoryMapper.delete(id);
    }
    //// 新增菜品时套餐时查询的分类信息
    @Override
    public List<Category> findByType(Integer type) {
    // 构建条件
        LambdaQueryWrapper<Category> lw=new LambdaQueryWrapper<>();
        lw.eq(Category::getType, type); // 根据类型  type= 1
        lw.orderByAsc(Category::getSort);// 分类升序 order by sort asc
        // 调用mapper查询，并返回
       return categoryMapper.selectList(lw);
    }
}
